package com.fingard.dsp.bank.directbank.cmbunion02;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fingard.common.utils.json.JSONUtils;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.SendBankRespose;
import com.fingard.dsp.bank.directbank.cmbunion02.utils.MD5Utils;
import com.fingard.dsp.bank.directbank.cmbunion02.utils.SignatureUtil;
import com.fingard.dsp.bank.directbank.fngrd01.util.ExcelUtil;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqUnifiedOrder;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.util.*;

public class CMBUnion02Base extends DirectBase {
    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }
    /**
     * 把单位由元换算成单位为分
     * @param amount 金额（元）
     */
    public String changeCurToFen(String amount){
        BigDecimal bigDecimal = new BigDecimal(amount);
        return bigDecimal.multiply(new BigDecimal(100)).setScale(0).toString();
    }
    /**
     * 把订单有效时间由分转成秒
     */
    public String changeToMIn(ReqUnifiedOrder p_req) throws ParseException {
        String validTime = "";

        long timeOut = p_req.getTimeExpire().getTime() - p_req.getTimeStart().getTime();
        validTime = String.valueOf(timeOut / 1000);
        return validTime;
    }
    public HashMap<String, String> getOpenid(String p_appId, String p_appSecret, String p_code) {
        HashMap<String, String> retHash = new HashMap<String, String>();

        String respCode = "";
        String respInfo = "";

        String tmpUrl = bankFront.getUrl("access_token");
        if (StringHelper.isNullOrEmpty(tmpUrl)) {
            respCode = "-1";
            respInfo = "未设置“通过code换取网页授权access_token”的地址,请检查BankFront.xml相关配置!";
        } else {
            tmpUrl = tmpUrl + "?appid=" + p_appId + "&secret=" + p_appSecret + "&code=" + p_code
                    + "&grant_type=authorization_code";
            WriteBankLogStep2(tmpUrl);

            WebRequest tmpWebRequest = new WebRequest(tmpUrl);
            String[] tmpRet = tmpWebRequest.upload(null, getCharset());
            if (tmpRet[0].length() == 0) {
                WriteBankLogStep3(tmpRet[1]);

                if (tmpRet[1].startsWith("{")) {
                    retHash = JSONUtils.json2Map(tmpRet[1]);
                    respCode = "0";
                } else {
                    respCode = "-1";
                    respInfo = tmpRet[1];
                }
            } else {
                respCode = "-1";
                respInfo = tmpRet[1];
                WriteBankLogLn(tmpRet[0] + "\r\n" + tmpRet[1]);
            }
        }

        retHash.put("RespCode", respCode);
        retHash.put("RespInfo", respInfo);

        return retHash;
    }
    public Map<String, String> removeHead(Map<String, String> tmpMapParams) {
        tmpMapParams.remove("BankCode");
        tmpMapParams.remove("TransType");
        tmpMapParams.remove("CommandCode");
        tmpMapParams.remove("Entity");
        return tmpMapParams;
    }
    public Map<String, String> getCommonMap(){
        Map<String, String> requestPublicParams = new TreeMap<String, String>();
        requestPublicParams.put("version", "0.0.1");    //版本号，固定为0.0.1(必传字段)
        requestPublicParams.put("encoding", "UTF-8");   //编码方式，固定为UTF-8(必传)
        requestPublicParams.put("signMethod", "01");    //签名方法，固定为01，表示签名方式为RSA2(必传)
        return requestPublicParams;
    }
    protected String[] sendToBank(String sign, String p_reqStr, String url, ActSetItem actItem) throws Exception{
        String[] retStr = new String[]{"",""};
        WriteBankLogStep2(p_reqStr);
        Map<String,String> apiSign = new TreeMap<String,String>();
        apiSign.put("appid", actItem.appIdMap.get("MD5"));
        apiSign.put("secret", actItem.appSecretMap.get("MD5"));
        apiSign.put("sign", sign);
        String timestamp = "" + System.currentTimeMillis()/1000;
        apiSign.put("timestamp", timestamp);
        // MD5加密
        String MD5Content = SignatureUtil.getSignContent(apiSign);
        String apiSignString = MD5Utils.getMD5Content(MD5Content).toLowerCase();
        WriteBankLogLn("报文头MD5加密后为："+apiSignString);
        WebRequest tmpWebRequest = new WebRequest(url);
        tmpWebRequest.setRequestProperty("appid", actItem.appIdMap.get("MD5"));
        tmpWebRequest.setRequestProperty("Content-Type", "application/json");
        tmpWebRequest.setRequestProperty("timestamp", timestamp);
        tmpWebRequest.setRequestProperty("apisign", apiSignString);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("connection", "Close");
        byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
    /**
     * 返回HTTP字符串转MAP
     *
     * @return
     */
    public static Map<String,String> convertToMap(String srcStr) {
        Map<String,String> params = new HashMap<String,String>();

        String[] nodes = srcStr.split("&");
        for (String node : nodes) {
            int index = node.indexOf("=");

            String key = node.substring(0, index);
            String value = node.substring(index+1);

            params.put(key, value);
        }

        return params;
    }
    protected SendBankRespose smsGet(String p_url, String filePath, String billRequestType) {
        SendBankRespose retResp = new SendBankRespose();

        URL url = null;
        HttpURLConnection httpUrlConnection = null;
        InputStream fis = null;
        FileOutputStream fos = null;

        try {

            url = new URL(p_url);
            httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setConnectTimeout(50 * 1000);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setRequestMethod("GET");
            httpUrlConnection.setRequestProperty("Charset", "UTF-8");
            httpUrlConnection.connect();
            fis = httpUrlConnection.getInputStream();
            byte[] temp = new byte[1024];
            int b;
            fos = new FileOutputStream(new File(filePath));
            while ((b = fis.read(temp)) != -1) {
                fos.write(temp, 0, b);
                fos.flush();
            }

            String content = "";
            if ("new".equalsIgnoreCase(billRequestType)) {
                content = ExcelUtil.read(filePath, 14);
            } else {
                content = ExcelUtil.read(filePath);
            }
            WriteBankLogStep3(content);
            retResp.retMessage =  content;
        } catch (Exception e) {
            retResp.connState = FailCode.E9999;
            retResp.retMessage = e.getMessage();
            retResp.appendLog(e);
            return retResp;
        } finally {
            try {
                if(fis!=null) fis.close();
                if(fos!=null) fos.close();
                if(httpUrlConnection!=null) httpUrlConnection.disconnect();
            } catch (IOException e) {
                this.WriteBankLogLn(e);
            }
        }

        return retResp;
    }
}
